import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * servlet程序， 实现表白墙后台逻辑
 */
class Message{
    public String from;
    public String to;
    public String message;
}

@SuppressWarnings({"all"})
@WebServlet("/message")
public class MessageServlet extends HttpServlet {

    private ObjectMapper objectMapper = new ObjectMapper(); // 用于解析 json

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理提交消息请求
        Message message = objectMapper.readValue(req.getInputStream(), Message.class); // 读取 json
        save(message); // 存储
        // 通过 ContentType 来告知页面, 返回的数据是 json 格式.
        // 有了这样的声明, 此时 jquery ajax 就会自动的帮我们把字符串转成 js 对象.
        // 如果没有, jquery ajax 就只是当成字符串来处理的~~
        resp.setContentType("application/json; charset=utf8");
        resp.getWriter().write("{ \"ok\": true }");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取到消息列表. 只要把消息列表中的内容整个的都返回给客户端即可
        // 此处需要使用 ObjectMapper 把 Java 对象, 转成 JSON 格式字符串~
        List<Message> messages = load(); // 获取数据
        String jsonString = objectMapper.writeValueAsString(messages);
        System.out.println("jsonString: " + jsonString);
        resp.setContentType("application/json; charset=utf8");
        resp.getWriter().write(jsonString);
    }

    /**
     * 将一条消息保存到数据库中
     * @param message 要保存的数据
     */
    private void save(Message message){
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            // 1. 和数据库连接
            connection = DBUtil.getConnection();
            // 2. 构造 sql
            String sql = "insert into message values(?, ?, ?)";
            statement = connection.prepareStatement(sql);
            statement.setString(1, message.from);
            statement.setString(2, message.to);
            statement.setString(3, message.message);
            // 3. 执行 sql
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 4. 释放资源
            DBUtil.close(connection, statement, null);
        }
    }

    /**
     * 从数据库中获取到所有的表白信息
     * @return 返回一个List，存储的就是表白信息
     */
    private List<Message> load(){
        List<Message> messages = new ArrayList<>();
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            // 1. 和数据库连接
            connection = DBUtil.getConnection();
            // 2. 构造 sql
            String sql = "select * from message";
            statement = connection.prepareStatement(sql);
            // 3. 执行 sql
           resultSet = statement.executeQuery();
            // 4. 存储
            while (resultSet.next()){
                Message message = new Message();
                message.from = resultSet.getString("from");
                message.to = resultSet.getString("to");
                message.message = resultSet.getString("message");
                messages.add(message);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 4. 释放资源
            DBUtil.close(connection, statement, resultSet);
        }
        return messages;
    }
}
